package com.zx.map.service.impl;

import com.zx.exception.GlobalServiceException;
import com.zx.map.dao.ShareProfitLogDao;
import com.zx.map.dao.model.AgentInfo;
import com.zx.map.dao.model.ShareProfitLog;
import com.zx.map.dao.model.ShareProfitLogExample;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.BaseAcctInfoService;
import com.zx.map.service.CustAcctLogService;
import com.zx.map.service.ShareProfitLogService;
import com.zx.map.service.model.*;
import com.zx.mobile.domain.TransferShareProfitDomain;
import com.zx.mobile.service.proxy.ShareProfitServiceProxy;
import com.zx.platform.service.RolesService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 14-3-1 Time: 上午11:07 To
 * change this template use File | Settings | File Templates.
 */
@Component("shareProfitLogService")
public class ShareProfitLogServiceImpl implements ShareProfitLogService {
    /**
     * log
     */
    private static Logger log = Logger
            .getLogger(ShareProfitLogServiceImpl.class);

    @Autowired
    private ShareProfitLogDao shareProfitLogDao;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private CustAcctLogService custAcctLogService;
    @Autowired
    private BaseAcctInfoService baseAcctInfoService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private RolesService rolesService;



    /**
     * 获取该代理分享收益  根据用户ID
     *
     * @param custId
     * @return
     * @throws DataAccessException
     */
    public ShareProfitLogModel queryProfitByCustId(String custId) throws DataAccessException {
        ShareProfitLogModel param = new ShareProfitLogModel();
        param.setCustId(custId);
        List<ShareProfitLogModel> list = getListByModel(param);
        if (null != list && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }
    /**
     * 获取该代理分享收益  根据用户账户
     *
     * @param custSysAccount
     * @return
     * @throws DataAccessException
     */
    public ShareProfitLogModel queryProfitByCustSysAccount(String custSysAccount) throws DataAccessException {
        ShareProfitLogModel param = new ShareProfitLogModel();
        param.setCustSysAccount(custSysAccount);
        List<ShareProfitLogModel> list = getListByModel(param);
        if (null != list && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }


    /**
     * 根据Model查找列表
     */
    public List<ShareProfitLogModel> getListByModel(ShareProfitLogModel model)
            throws DataAccessException {
        ShareProfitLogExample example = new ShareProfitLogExample();
        ShareProfitLogExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(model.getCustId())) {
            criteria.andCustIdEqualTo(model.getCustId());
        }
        if (StringUtils.isNotBlank(model.getCustSysAccount())) {
            criteria.andCustSysAccountEqualTo(model.getCustSysAccount());
        }
        example.setOrderByClause("CREATE_DATE DESC");
        List<ShareProfitLog> list = shareProfitLogDao.getListByExample(example);
        List<ShareProfitLogModel> modelList = new ArrayList<ShareProfitLogModel>();
        for (ShareProfitLog o : list) {
            ShareProfitLogModel temp = new ShareProfitLogModel();
            BeanUtils.copyProperties(o, temp);
            modelList.add(temp);
        }
        return modelList;
    }

    /**
     * 分页查询
     *
     * @param pageSize
     * @param pageNum
     * @param model
     * @return
     * @throws DataAccessException
     */
    @Deprecated
    public Map getPageByDomain(int pageSize, int pageNum, ShareProfitLogModel model)
            throws DataAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        ShareProfitLogExample example = new ShareProfitLogExample();
        ShareProfitLogExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(model.getCustId())) {
            criteria.andCustIdEqualTo(model.getCustId());
        }
        if (StringUtils.isNotBlank(model.getCustSysAccount())) {
            criteria.andCustSysAccountEqualTo(model.getCustSysAccount());
        }
        example.setOrderByClause("CREATE_DATE DESC");
        int pageBegin = (pageNum - 1) * pageSize;
        List<ShareProfitLog> list = shareProfitLogDao.getPageByExample(pageSize,pageBegin,example);
        List<ShareProfitLogModel> modelList = new ArrayList<ShareProfitLogModel>();
        for (ShareProfitLog o : list) {
            ShareProfitLogModel temp = new ShareProfitLogModel();
            BeanUtils.copyProperties(o, temp);
            modelList.add(temp);
        }
        int count = shareProfitLogDao.countListByExample(example);
        map.put("count", count);
        map.put("list", modelList);
        return map;
    }

    /**
     * 查询下级代理商 分享收益
     * @param currentLoginAgentInfo
     * @param shareProfitLogModel
     * @return
     */
    @Override
    public Map<String,Object> queryShareProfitLog(AgentInfoModel currentLoginAgentInfo,AgentInfoModel searchAgentInfoModel, ShareProfitLog shareProfitLogModel) {
        Map<String, Object> map = new HashMap<String, Object>();

        List<String> agentIdList=agentInfoService.queryDownAgentIdList(currentLoginAgentInfo,searchAgentInfoModel);
        ShareProfitLogExample example = new ShareProfitLogExample();
        ShareProfitLogExample.Criteria criteria = example.createCriteria();
        if (agentIdList == null || agentIdList.isEmpty()) {
            agentIdList.add("-1");
            log.debug("下级代理空");
        }
        log.debug("下级代理长度"+agentIdList.size()+" "+agentIdList.toString());
        criteria.andCustIdIn(agentIdList);
        example.setOrderByClause("CREATE_DATE DESC");

        int beginIndex=(shareProfitLogModel.getPageNum()-1)*shareProfitLogModel.getPageSize();
        List<ShareProfitLog> list = shareProfitLogDao.getPageByExample(shareProfitLogModel.getPageSize(),beginIndex,example);

        for(ShareProfitLog shareProfitLog : list){
            AgentInfoModel agentInfoModelTmp=agentInfoService.getModelByKey(shareProfitLog.getCustId());
            String level = agentInfoModelTmp.getAgentLevel();
            String roleName=rolesService.getLevelNameByRoleId(level).getRoleName();
            String agentName=agentInfoModelTmp.getAgentName();
            shareProfitLog.setRoleName(roleName);
            shareProfitLog.setAgentName(agentName);
        }
        int count = shareProfitLogDao.countListByExample(example);
        double sprofitBal = shareProfitLogDao.countSprofitBal(example);
        double sprofitAvlAmt = shareProfitLogDao.countSprofitAvlAmt(example);

        map.put("sprofitBal",sprofitBal);
        map.put("sprofitAvlAmt",sprofitAvlAmt);
        map.put("count", count);
        map.put("list", list);
        return map;
    }


    /**
     * 新增
     */
    public String add(ShareProfitLogModel model) throws DataAccessException {
        ShareProfitLog temp = new ShareProfitLog();
        BeanUtils.copyProperties(model, temp);
        String key = shareProfitLogDao.add(temp);
        return key;
    }

    /**
     * 修改
     */
    public String update(ShareProfitLogModel model) throws DataAccessException {
        ShareProfitLog temp = new ShareProfitLog();
        BeanUtils.copyProperties(model, temp);
        return shareProfitLogDao.update(temp);
    }

    /**
     * 删除
     */
    public void delete(ShareProfitLogModel model) throws DataAccessException {
        ShareProfitLog temp = new ShareProfitLog();
        BeanUtils.copyProperties(model, temp);
        shareProfitLogDao.delete(temp);
    }

    /**
     * 分享收益转出
     */
    @Override
    public void transferShareProfit(
            final TransferShareProfitDomain transferShareProfitDomain, final MerchantInfoModel curMerchantInfoModel) {

        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus arg0) {
                //1、增加行锁读
                BaseAcctInfoModel temp = baseAcctInfoService.getModelByKeyAndLineLock(curMerchantInfoModel.getMerchantId());
                //2、业务逻辑进行判断
                ShareProfitLogModel spTemp = queryProfitByCustSysAccount(curMerchantInfoModel.getSysAccount());
                if (null != spTemp && spTemp.getSprofitAvlAmt() >= Double.parseDouble(transferShareProfitDomain.getTradeAmt())) {
                    //3、允许转出情况下 进行业务逻辑处理
                    //分享收益转出更新
                    ShareProfitLogModel newModel = ShareProfitServiceProxy.transformSpModel(spTemp,
                            transferShareProfitDomain.getTradeAmt().toString());
                    update(newModel);
                    // 账户增加
                    temp = ShareProfitServiceProxy.transformBaseAcct(temp,
                            transferShareProfitDomain.getTradeAmt().toString());
                    CustAcctLogModel custModel = ShareProfitServiceProxy.transformCustAcct(temp, spTemp,
                            transferShareProfitDomain.getTradeAmt());
                    custAcctLogService.add(custModel);
                    baseAcctInfoService.update(temp);
                } else {
                    //3、在不符合业务规范的 异常抛出
                    throw new GlobalServiceException("收益转出金额超过可用余额");
                }
                return null;
            }
        });

    }
}
